/*
* @Author: Yangrui
* @Date: 2023-05-30 15:57:02
* @LastEditors: Yejing
* @LastEditTime: 2023-06-08 15:39:55
* @Description: desc
*/
<template>
	<view class="media-view" :style="paddingStyle">
		<view class="header">
			<c-status-bar :isFixed="false" />
			<view class="header-content">
				<view class="">
					<imageForSize @click="backOption" size="36" :src="require('@/static/images/user/left.png')">
					</imageForSize>
				</view>
				<view v-if="taskInfo.offlineId" style="color: #fff;font-size: 32rpx;">
					<text v-if="taskTimer.count">{{taskTimer.count}}s</text>
					<text v-else>{{$t('media.tsakDone')}}</text>
				</view>
			</view>

		</view>
		<view class="zan-count-box" v-if="taskInfo.offlineId">
			<view class="top-box" v-if="taskInfoCount">
				<view style="text-align: center;">{{$t('media.taskText')}}</view>
				<view style="display: flex;align-items: center;justify-content: space-between;flex-wrap: wrap;">
					<!--  -->
					<view v-if="taskInfo.collectCount">{{$t('media.click3')}}：<text
							v-if="offLineData.collect<taskInfo.collectCount">{{offLineData.collect}}/{{taskInfo.collectCount}}{{$t('media.number')}}</text>
						<text v-else>{{$t('media.done')}}</text>
					</view>
					<view v-if="taskInfo.heartCount">{{$t('media.click1')}}：<text
							v-if="offLineData.heart<taskInfo.heartCount">{{offLineData.heart}}/{{taskInfo.heartCount}}{{$t('media.number')}}</text>
						<text v-else>{{$t('media.done')}}</text>
					</view>
					<view v-if="taskInfo.zanCount">{{$t('media.click2')}}：<text
							v-if="offLineData.zan<taskInfo.zanCount">{{offLineData.zan}}/{{taskInfo.zanCount}}{{$t('media.number')}}</text>
						<text v-else>{{$t('media.done')}}</text>
					</view>
				</view>
			</view>
		</view>
		<swiper v-if="videoList.length != 0 && (!backTimer.timer)" :vertical="true" @change="changeCurrentVideo"
			interval="1000" :current="recordCurrent">
			<swiper-item v-for="(item, index) in videoList" :key="item.id+''+index">
				<c-video ref="cVideo" @openSharePop="openSharePop" :videoCurrent="videoCurrentKey" :video="item"
					@play="videoPlay" @pause="videoPause" @error="loadError" @wait="videoWait"
					@timeupdate="videoTimeUpdate" :taskInfo="taskInfo" :offLine="offLineData"
					@offOnlineClick="offOnlineClick"></c-video>
			</swiper-item>
		</swiper>
		<view v-else class="none-video">
			<u-icon name="play-circle" color="rgba(255,255,255,0.5)" size="128"></u-icon>
			<text class="no-video">No video</text>
		</view> -->
		<c-share v-model="shareShow"></c-share>
		<u-mask :show="!!backTimer.count" class="time-mask">
			<view class="time-warp">
				<view class="">
					<h1 style="color: #fff;" :key="backTimer.count">
						<text v-if="backTimer.count<=3">{{backTimer.count}}</text>
					</h1>
				</view>
				<view class="">
					<text @click="immediatelyBack">{{$t('media.return')}}</text>
				</view>
			</view>
		</u-mask>
	</view>
</template>
<script>
	import cVideo from '@/pages/media/components/c-video.vue'
	let first = true
	export default {
		components: {
			cVideo
		},
		onUnload() {
			this.taskTimer.timer && clearInterval(this.taskTimer.timer)
		},
		onHide() {},
		onShow() {

		},
		beforeRouteEnter() {
			console.log(arguments, '路由进入');
		},
		data() {
			return {
				// swiper组件是否自动滑动
				autoplay: false,
				// 任务标题
				title: "",
				// 任务info
				info: "",
				// 广告弹窗
				memberAdvertisingShow: false,
				setInterval: null,
				popData: {},
				popShop: false,
				videoCurrent: '', // 当前滑动视频id
				// 顶部列表
				tabList: [{
						name: "Followed",
						id: 2,
						path: "/pages/Followed/index"
					},
					{
						name: "Recommend",
						id: 3,
						path: "/pages/Recommend/index"
					},
				],
				// 当前列表显示索引
				current: 0,
				videoList: [],
				// 
				shareShow: false,
				// 当前视频模式 如果没有记录就是随机加载 历史记录存于vuex
				recordStatus: false,
				// 短视频记录
				recordList: [],
				recordNo: 0,
				recordCurrent: 0,
				// 返回计时对象
				backTimer: {
					timer: null,
					count: 0
				},
				// 任务计时对象
				taskTimer: {
					timer: null,
					count: '',
					finish: false
				},
				taskInfo: {},
				videoWaitTimer: null, // 视频等待计时
				offLineData: {
					zan: 0,
					collect: 0,
					heart: 0
				}, // 线下理财的数据
			};
		},
		onLoad(data) {
			if (data.videoId || data.offlineId) {
				if (data.offlineId) {
					this.taskInfo = {
						...data,
						zanCount: ~~data.zanCount,
						collectCount: ~~data.collectCount,
						heartCount: ~~data.heartCount
					}
					console.log(data, data.time);
					this.taskTimer = {
						...this.taskTimer,
						count: data.time
					}
					console.log(this.taskTimer);
					this.urlVideoIdOfflineAjax()
				} else {
					this.urlVideoIdAjax(data.videoId)
				}
			} else {
				this.recordVideoInit()
			}
		},
		computed: {
			paddingStyle() {
				let style = {}
				style = {
					'padding-bottom': this.$store.getters.homePageWindowInfo.safeArea
				}
				return style
			},
			videoCurrentKey() {
				return `videoObj_${this.videoCurrent}`
			},
			// 是否存在 任务计算数量的
			taskInfoCount() {
				console.log(this.taskInfo.zanCount || this.taskInfo.collectCount || this.taskInfo.heartCount);
				console.log(this.taskInfo.zanCount, this.taskInfo.collectCount, this.taskInfo.heartCount);
				return this.taskInfo.zanCount || this.taskInfo.collectCount || this.taskInfo.heartCount
			},
			// 判断任务是否完成
			taskInfoCountFinish() {
				if (this.taskInfoCount) {
					let status = false
					Object.keys(this.offLineData).every((item) => {
						status = this.offLineData[item] >= this.taskInfo[item + 'Count']
						return status
					})
					return status
				} else { // 没有任务 --- 返回完成
					return true
				}
			},
		},
		methods: {
			offOnlineClick(key) {

			},
			getNewVedioAjax(cb) {
				return new Promise((r1, r2) => {
					this.$u.get("/app/short/video").then(res => {
						if (res.data) {
							this.videoList.push(res.data)
							cb && cb()
							r1(res.data)
						}
					})
				})
			},
			// 滑动事件暂停其他所有视频，播放当前视频
			changeCurrentVideo(e) {
				this.autoplay = false
				this.videoCurrent = this.videoList[e.detail.current].id
				this.currtentChange(e.detail.current)
			},
			openSharePop() {
				console.log('openSharePop');
				this.shareShow = !this.shareShow
			},
			goSearch() {
				this.$u.route('pages/searchInfo/videoSearch')
			},
			// 记录视频初始化
			recordVideoInit() {
				let storeName = uni.getSystemInfoSync().appName + 'Store'
				const loaclData = (this.publicJS.tryGet(() => uni.getStorageSync(storeName).vuex_video_record) || {})
				const videoRecordData = this.vuex_video_record.list.length ? this.vuex_video_record : loaclData
				// 获取状态机中的视频列表
				this.videoList = videoRecordData.list.map(m => ({
					...m,
					id: m.videoId
				}))
				// 设置当前视频的index
				this.$set(this, 'recordCurrent', videoRecordData.index)
				const id = this.videoList[this.recordCurrent].videoId
				this.getVideoInfoAjax(id)
				this.initPlay(id)

			},
			initPlay(id = this.videoList[this.recordCurrent].videoId) {
				this.$nextTick(() => {
					this.videoCurrent = id
					const refs = this.$refs.cVideo[this.recordCurrent]
					refs.flag = '1'
					refs.changeVideoStatus(
						`videoObj_${this.videoList[this.recordCurrent].id}`)
				})
			},
			backOption() {
				this.publicJS.backOption()
			},
			// 切换
			currtentChange(index) {
				const curretnt = this.videoList[index]
				if (curretnt.userId) {
					return
				}
				this.getVideoInfoAjax(curretnt.id)
			},
			// 获取视频详情信息
			getVideoInfoAjax(id) {
				this.$u.get('/app/short/video/' + id).then(res => {
					this.videoList = this.videoList.map(f => f.id === id ? {
						...f,
						...res.data
					} : f)
				this.$forceUpdate()
				}).catch(err => {
					this.$u.toast(this.$t('media.videoMissing'), 1000)
					this.timeBack()
				})
			},
			// 通过url上的id获取短视频
			urlVideoIdAjax(id) {
				console.log('id: ', id);
				this.$u.get('/app/short/video/' + id).then(res => {
					this.videoList = [res.data]
					this.initPlay()
				}).catch(err => {
					this.$u.toast(this.$t('media.videoMissing'), 1000)
					this.timeBack()
				})
			},
			// 通过url上的id获取短视频
			urlVideoIdOfflineAjax(id) {
				this.$u.get('/app/offlineShortVideo/getVideoInfo').then(res => {
					console.log(res.data);
					this.videoList = [{
						...res.data,
						// url: 'short_video/2023-08-09/16915502793965326'
					}]
					this.taskInfo.videoId = res.data.id
					this.initPlay()
				}).catch(err => {
					this.$u.toast(this.$t('media.videoMissing'), 1000)
					this.timeBack()
				})
			},
			// 计时返回
			timeBack() {
				const timer = setInterval(() => {
					this.backTimer = {
						...this.backTimer,
						count: this.backTimer.count + 1
					}
					if (this.backTimer.count === 4) {
						this.immediatelyBack()
					}
				}, 1000)
				this.backTimer = {
					...this.backTimer,
					timer
				}
			},
			// 返回操作
			immediatelyBack() {
				this.publicJS.backOption()
				clearInterval(this.backTimer.timer)
			},
			// 播放
			videoPlay(video) {
				if (this.taskInfo.offlineId) {
					this.taskInit()
				}
			},
			// 暂停	
			videoPause(video) {
				if (this.taskInfo.offlineId) {
					clearInterval(this.taskTimer.timer)
					this.taskTimer.timer = null
				}
			},
			// 任务初始化
			taskInit() {
				if (this.taskTimer.timer || this.taskTimer.finish) {
					return
				}
				this.taskTimer.timer = setInterval(() => {
					this.taskTimer = {
						...this.taskTimer,
						count: this.taskTimer.count - 1
					}
					if (!this.taskTimer.count) {
						this.finishTask()
					}
				}, 1000)
			},
			// 完成任务
			finishTask(data) {
				console.log(data,
					'/app/financial/offline/user/finish/task/app/financial/offline/user/finish/task/app/financial/offline/user/finish/task/app/financial/offline/user/finish/task'
				);
				this.taskTimer.finish = true
				this.videoPause()
				this.taskTimer.count = ''
				if (this.taskInfoCount) {
					if (this.taskInfoCountFinish) {

					} else {
						this.$u.toast(this.$t('media.taskDemand'))
						return
					}
				}
				this.visableTaskFinish()

			},
			// 加载失败
			loadError() {
				this.$u.toast(this.$t('media.videoMissing'), 1000)
				this.timeBack()
			},
			videoWait() {
				// 不知道为什么视频缓冲后会执行一次视频进度条变化的事件所有设置了一个延时器。
				(!this.videoWaitTimer) && (this.videoWaitTimer = setTimeout(() => {
					this.videoWaitTimer = null
					clearTimeout(this.videoWaitTimer)
				}, 300));
				this.videoPause()
			},
			// 函数应该是代表着 
			videoTimeUpdate(e) {
				if (this.videoWaitTimer) {
					return
				}
				this.videoPlay()
			},
			// 线下理财相关按钮点击
			offOnlineClick(key) {
				// 记录加一后的数目
				const count = this.offLineData[key] + 1
				// 如果 相加的额数量大于 任务数量则 不执行后续步骤
				if (count > this.taskInfo[key + 'Count']) {
					return
				}
				this.offLineData[key] = count
				if (this.taskInfoCountFinish && this.taskTimer.count <= 0) {
					this.visableTaskFinish()
				}
			},
			// 校验点赞那些的完成情况
			visableTaskFinish() {
				const data = {
					offlineId: this.taskInfo.offlineId,
					number: this.taskInfo.sort,
					videoIds: [this.taskInfo.videoId]
				}
				console.log(data);
				this.$u.post(`/app/financial/offline/user/finish/task`, data).then(res => {
					uni.$u.init.getUserInfo(null, false)
					this.$u.toast(this.$t('media.tsakDon2'))
				})
			},
		},
		// mounted() {

		// },
	}
</script>

<style lang="scss" scoped>
	page {
		background: black;
	}

	.media-view {
		background: black;
		width: 100vw;
		height: 100vh;
		overflow: hidden;
	}

	swiper {
		height: 100%;
	}

	.swiper-item {
		height: 100%;

		video {
			height: 100%;
			width: 100%;
		}

		.user {
			position: fixed;
			left: 30rpx;
			color: white;
			bottom: 100rpx;
			display: flex;
			flex-direction: column;
			width: 50%;
		}

		// .Task_rewards {
		// 	position: fixed;
		// 	right: 30rpx;
		// 	color: white;
		// 	bottom: 50rpx;
		// 	display: flex;
		// 	width: 50%;
		// 	flex-direction: column;
		// 	align-items: flex-end;

		// 	.coin {
		// 		background: url('@/static/image/offlineVideo/coin.png');
		// 		width: 150rpx;
		// 		height: 150rpx;
		// 		background-position: center;
		// 		background-size: contain;
		// 		display: flex;
		// 		align-items: center;
		// 		justify-content: space-evenly;

		// 		view {
		// 			display: flex;
		// 			flex-direction: column;
		// 			align-items: center;
		// 			justify-items: center;
		// 		}
		// 	}
		// }
	}

	.header {
		position: fixed;
		top: 30rpx;
		left: 0;
		font-size: 24rpx;
		z-index: 100;
		width: 100vw;

		.header-content {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			padding-right: 32rpx;
			padding-left: 44rpx;

			cover-image {
				width: 45rpx;
				height: 45rpx;
			}

			.cover-tabs-box {
				flex: auto;
				display: flex;
				align-items: flex-end;

				.cover-tabs {
					font-size: 32rpx;
					color: #fff;
					opacity: 0.5;

					&+.cover-tabs {
						margin-left: 20rpx;
						padding-left: 4rpx;
					}

					&.is-active {
						padding-left: 0;
						font-size: 40rpx;
						opacity: 1;
					}
				}
			}
		}

		/deep/ .u-tabs {
			background: unset !important;
		}
	}

	.zan-count-box {
		position: fixed;
		top: 130rpx;
		left: 50%;
		width: 550rpx;
		transform: translateX(-50%);
		z-index: 99;
		font-size: 24rpx;
		background-color: rgba(0, 0, 0, 0.3);
		color: #FFFFFF;
		border-radius: 10rpx;

		.top-box {
			padding: 10rpx 30rpx;
		}
	}

	.zhuanfaPopup {

		.zhuanfaScrollView {
			padding: 60rpx 50rpx;

			/deep/ .uni-scroll-view-content {
				display: flex;
			}

			.zhuanfaItem {
				width: 150rpx;
				height: 150rpx;
				margin-right: 50rpx;
				flex-shrink: 0;

				image {
					width: 100%;
					height: 100%;
					border-radius: 25rpx;
				}
			}
		}

		.friendScrollView {
			height: 800rpx;


			.friend {
				display: flex;
				align-items: center;
				padding: 30rpx 46rpx;

				image {
					width: 100rpx;
					height: 100rpx;
					margin-right: 30rpx;
					border-radius: 50%;
				}

				.content {
					flex: 1;
					margin-right: 30rpx;

					.name {
						font-size: 34rpx;
						font-family: SFUIDisplay-Regular, SFUIDisplay;
						font-weight: 400;
						color: #0A1F44;
					}

					.info {
						font-size: 30rpx;
						font-family: SFUIDisplay-Regular, SFUIDisplay;
						font-weight: 400;
						color: #999CAD;
					}

					display: flex;
					flex-direction: column;
				}

				.btn {
					border: 2rpx solid #2934D0;
					border-radius: 12rpx;
					font-size: 28rpx;
					font-family: SFUIDisplay-Regular, SFUIDisplay;
					font-weight: 400;
					color: #2934D0;
					line-height: 40rpx;
				}
			}
		}
	}

	.none-video {
		height: 100%;
		width: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.no-video {
			color: rgba(255, 255, 255, 0.5);
			font-size: 48rpx;
		}
	}

	.time-mask {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;

		.time-warp {
			width: 200rpx;
			height: 200rpx;
			border-radius: 50%;
			padding: 40rpx;
			background-color: #ccc;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			>view {
				width: 100%;
				text-align: center;
			}
		}
	}
</style>